<template>
  <div>
    <!-- 添加消息输入框 -->
    <div class="message-input-container">
      <el-form :model="messageForm" size="small">
        <el-form-item label="添加消息" class="message-form-item">
          <tiptap-editor
            ref="messageEditor"
            v-model="messageForm.content"
            :height="80"
            :menubar="false"
            placeholder="输入消息内容..."
          />
        </el-form-item>
        <el-form-item class="message-actions">
          <el-button type="primary" size="small" :loading="sendingMessage" @click="sendMessage">
            发送消息
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row>
      <el-timeline :reverse="false">
        <el-timeline-item
          v-for="(activity, index) in data"
          :key="index"
          v-loading="listLoading"
          placement="top"
          :timestamp="activity.create_at"
        >
          <el-card>
            <h4>{{ activity.operate }}</h4>
            <p>{{ activity.description }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-row>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmoperationlog'
import TiptapEditor from '@/components/Tiptap'
import qs from 'qs'
const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmoperationlog',
  components: {
    TiptapEditor
  },
  props: ['order_data'],
  data() {
    return {
      listLoading: false,
      editloading: false,
      data: [],
      action: 'create',
      kwInput: '',
      order_by: '',
      order_desc: orderMapper[0],
      // pagination
      pagesize: 20,
      page: 1,
      total: 0,
      // 消息输入相关
      messageForm: {
        content: ''
      },
      sendingMessage: false
    }
  },
  watch: {
    order_data: {
      handler(v) {
        this.getList()
      },
      immediate: true // 立即触发一次 handler
    }
  },
  methods: {
    handleShowEdit() {
      this.childFormVisible = true
      this.action = 'create'
    },
    resetTemp() {
      this.CRMShippingInquiryTemp = {
        product_name: '',
        price_usd: 0,
        image: '',
        packages_weight: 1,
        packages_length: 1,
        packages_hight: 1,
        packages_width: 1,
        packages_volume: 1,
        packages_quantity: 1,
        departure_port: '',
        destination_port: '',
        country: '',
        zip: '',
        state: '',
        city: '',
        address: '',
        has_electric_moto: false,
        has_oil: false,
        expected_shipping_vessel: '',
        customer_requirements: '',
        shipping_note: ''
        // 注意: creator 和 project 可能需要特殊处理，例如使用选择器
      }
    },
    getList() {
      this.listLoading = true
      this.data = []
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        crmorder_id: this.order_data.id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    confirm() {
      switch (this.action) {
        case 'create':
          this.CRMShippingInquiryTemp.crmorder_id = this.order_data.id
          Post(this.CRMShippingInquiryTemp).then((response) => {
            this.childFormVisible = false
            this.$emit('reload')
            this.notify('添加成功')
            this.getList()
          })
          break
        case 'delete':
          Delete(this.CRMShippingInquiryTemp.id).then((response) => {
            this.childFormVisible = false
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case 'edit':
          Put(this.CRMShippingInquiryTemp.id, this.CRMShippingInquiryTemp).then((response) => {
            this.childFormVisible = false
            this.$emit('reload')
            this.notify('更新成功')
          })
          break
      }
    },
    cancel() {
      this.childFormVisible = false
    },
    hide() {
      this.$emit('close', false)
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    notify(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: 2000
      })
    },

    // 发送消息
    sendMessage() {
      if (!this.messageForm.content.trim()) {
        this.$message({
          message: '请输入消息内容',
          type: 'warning'
        })
        return
      }

      if (!this.order_data.id) {
        this.$message({
          message: '订单信息不完整',
          type: 'error'
        })
        return
      }

      this.sendingMessage = true

      const messageData = {
        operate: '添加消息',
        description: this.messageForm.content,
        object_id: `crmorder|${this.order_data.id}`
      }

      Post(messageData).then((response) => {
        this.sendingMessage = false
        this.messageForm.content = ''

        // 清空编辑器内容
        if (this.$refs.messageEditor) {
          this.$refs.messageEditor.clearContent()
        }

        this.$notify({
          title: '成功',
          message: '消息发送成功',
          type: 'success',
          duration: 2000
        })

        // 刷新消息列表
        this.getList()
      }).catch((error) => {
        this.sendingMessage = false
        this.$notify({
          title: '错误',
          message: '发送消息失败: ' + (error.message || error),
          type: 'error',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped>
  .mt-dialog >>> span.el-dialog__title {
    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: hidden;
  }

  .message-input-container {
    background-color: #f8f9fa;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 15px;
    margin-bottom: 20px;
  }

  .message-form-item {
    margin-bottom: 10px;
  }

  .message-actions {
    margin-bottom: 0;
    text-align: right;
  }

  .message-input-container >>> .tiptap-toolbar {
    display: none; /* 隐藏工具栏 */
  }

  .message-input-container >>> .tiptap-content {
    min-height: 60px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px 12px;
  }
</style>
